import { Component, OnInit } from '@angular/core';
import {NzMessageService, NzModalRef} from "ng-zorro-antd";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {AgentService} from "@core/routes-services/agent.service";

@Component({
  selector: 'app-agent-level-relate',
  templateUrl: './agent-level-relate.component.html',
  styles: []
})
export class AgentLevelRelateComponent implements OnInit {

  entity: any = {};
  validateForm: FormGroup;
  isLoading: boolean = false;

  type:any = 1;//1:合伙人关联  2： 执行董事关联

  agentList:any [] = [];
  activeList:any [] = [];
  passivityList:any [] = [];

  constructor(private fb: FormBuilder,
              private modal: NzModalRef,
              private agentService: AgentService,
              public message: NzMessageService,
  ) {
  }

  ngOnInit(): void {
    this.activeList = this.agentList;
    this.passivityList = this.agentList;
    this.validateForm = this.fb.group({
      activeRelatesId: [this.entity.activeRelatesId, [Validators.required]],
      passivityRelatesId: [this.entity.passivityRelatesId, [Validators.required]],
      type: [this.type, [Validators.required]],
    });
  }

  filterActiveList() {
    let that = this;
    this.activeList = this.agentList.filter((t) => t.id != that.validateForm.controls.passivityRelatesId.value );
  }
  filterPassivityList() {
    let that = this;
    this.passivityList = this.agentList.filter((t) => t.id != that.validateForm.controls.activeRelatesId.value );
  }

  submitForm(): void {
    if (this.validateForm.invalid) {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    } else {
      this.isLoading = true;
      this.agentService.saveOrUpdateRelate(this.entity.id, this.validateForm.value).then((res) => {
        if (res.status.toString().startsWith('20')) {
          this.modal.close(true);
        } else {
          this.message.warning(res.message);
        }
        this.isLoading = false;
      }, error => {
        this.message.error(error.message ? error.message : error.error);
        this.isLoading = false;
      });
    }
  }

  close() {
    this.modal.destroy();
  }

}
